﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Wy.JiZhangSoft.Notes.Dtos;

namespace Wy.JiZhangSoft.Notes
{
    [Authorize]
    public class NoteAppService : JiZhangSoftAppService
    {
        private readonly IRepository<Note> _noteRepository;

        public NoteAppService(IRepository<Note> noteRepository)
        {
            this._noteRepository = noteRepository;
        }

        public Task Add(NoteAddDto dto)
        {
            Note note = new Note();
            note.NoteType = dto.NoteType;
            note.Content = dto.Content;
            return _noteRepository.InsertAsync(note);
        }

        public async Task<NoteGetDto> Get(Guid id)
        {
            var note= await _noteRepository.SingleOrDefaultAsync(x => x.Id == id);
            return new NoteGetDto
            {
                Id = id,
                Content = note.Content,
                CreationTime = note.CreationTime.ToString("yyyy-MM-dd HH:mm"),
            };
        }

        public PagedResultDto<NoteGetDto> Get(NoteGetParameter input)
        {
            var notes = _noteRepository
                .Where(x => x.NoteType == input.NoteType && x.CreatorId == CurrentUser.Id)
                .OrderByDescending(x => x.CreationTime);
            var dto = new PagedResultDto<NoteGetDto>(notes.LongCount(), 
                notes.Skip(input.SkipCount)
                .Take(input.MaxResultCount)
                .Select(s => new NoteGetDto
            {
                Id = s.Id,
                Content = s.Show,
                CreationTime = s.CreationTime.ToString("yyyy-MM-dd HH:mm"),
                TotalCount = s.Content.Length
            }).ToList());
            return dto;
        }
    }
}
